import ImportData from "@/components/ImportData";
import { getFullTreeByXid, s_getPostWareInfo, s_getSelectData, s_getSelectTree, s_getTableInfo, s_operateInfo, s_updateInfo } from "@/services/basis";
import { ActionType, LabelIconTip, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormItem, ProFormRadio, ProFormSelect, ProFormText, ProTable, TableDropdown } from "@ant-design/pro-components";
import { useModel, useRequest } from "@umijs/max";
import { Button, Card, Col, Form, message, Modal, Row, Select, Space, Table, TableColumnProps, Tabs, TabsProps, Tag, Typography } from "antd";
import { isNull, isNumber } from "lodash";
import moment, { RFC_2822 } from "moment";
import React, { useRef, useState } from "react";

const App:React.FC=()=>{
    const [selectedRecords,setSelectedRecords]=useState<DataType[]>([]);
    const [selectedRecords2,setSelectedRecords2]=useState<DataType2[]>([]);
    const [open,setOpen]=useState(false);
 
    const [etype,setEtype]=useState(1);
    // const [areaSelect,setAreaSelect]=useState([]);

    const table_ref=useRef<ActionType>();
    const table_ref2=useRef<ActionType>();
    const form_ref=useRef<ProFormInstance>();

    const { initialState, setInitialState } = useModel('@@initialState');
    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);
    const [selectedLineKeys2,setSelectedLineKeys2]=useState<any[]>([]);
  
    interface DataType{
        x_id?:number,
        id?:number,
        code?:string,
        name?:string,
        type?:number,
        status?:number,
    }
    const columns:ProColumns<DataType>[]=[
        {key:'id',dataIndex:'id',title:'ID',hidden:true},{dataIndex:'x_id',hidden:true},
        {dataIndex:'code',title:'仓库编码'},{dataIndex:'name',title:'仓库名'}, 
        {dataIndex:'type',title:'类型',valueType:'radio',
            valueEnum:{1:{text:'普通仓'},2:{text:'线边仓'},3:{text:'VMI仓'}}
        },
        {dataIndex:'status',title:'状态',
            render:(text)=>text==1?<>正常</>:text==2?<Tag style={{color:'blue'}}>关闭</Tag>:<Tag style={{color:'red'}}>删除</Tag>},
    ];

    interface DataType2{
        id?:number,
        warehouse_id?:number,
        code?:string,
        name?:string,
        status?:number,
        operater_id:number,
        operater_name:string,
        operate_time?:string,
    }
    const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'id',title:'ID',key:'id'},
        {dataIndex:'code',title:'库位编号',},
        {dataIndex:'name',title:'库位名称',},
        {dataIndex:'operate_time',title:'操作时间',valueType:'date' },
        {dataIndex:'operater_name',title:'操作人',},
        {dataIndex:'status',title:'状态',
            render:(text)=>text==1?<>正常</>:text==2?<Tag style={{color:'blue'}}>关闭</Tag>:<Tag style={{color:'red'}}>删除</Tag>}
        
    ];
       
    async function add(){
      if(selectedRecords.length==0)
        message.warning('请先选择仓库');
      else{
        setEtype(1);
        setOpen(true);
      };
    };

    async function edit(){
      if(selectedRecords2.length==0)
         message.warning('请先选择要编辑的行。');
      else if(selectedRecords2[0].status==2||selectedRecords2[0].status==3)
         message.warning('已删除或关闭的档案，不能编辑。请先恢复');
      else{
         setEtype(0);
         setOpen(true);
         };
      }; 

    async function save(){
           var fdata=form_ref?.current?.getFieldsValue();
            if(etype==1)
               fdata={...fdata,warehouse_id:selectedRecords.length>0?selectedRecords[0].id:0};
           const x=await s_updateInfo({source:'base_warehouse_pos',x_id:1,operater_id:initialState?.currentUser?.userid,etype,fdata});
           
           if(x.success){
              message.success('数据保存成功。');
              setOpen(false);
              table_ref2.current?.reloadAndRest?.();
              setEtype(1);
           }else
           message.error('数据保存失败。');
        }; 
    

    async function operate(otype:number){
          setEtype(1);
          var id=0;
             if(selectedRecords2.length==0)
                 message.warning('请先选择要操作的行。');
             else{
                 id=selectedRecords2[0].id;
                const x=await s_operateInfo({source:'base_warehouse_pos',x_id:1,operater_id:initialState?.currentUser?.userid,otype,id});
                if(x.success){
                    message.success('数据更新成功。');
                    table_ref2.current?.reloadAndRest?.();
                    // setSelectedRecords2([]);
              }
                else
                    message.error('数据更新失败。');
                
               };
      };   

    return (
        <>
        <Row gutter={8}>
          <Col span={8}>
          <ProCard title='仓库列表' style={{height:'75vh'}}>
           <ProTable<DataType>
                rowKey='id'
                actionRef={table_ref}
                search={false}
                columns={columns}
                rowSelection={{
                    type:'radio',
                    selectedRowKeys:selectedLineKeys,
                    onChange:(selectedRowKeys,selectedRows)=>{
                            setSelectedRecords(selectedRows);
                            setSelectedLineKeys(selectedRowKeys);
                            table_ref2.current?.reloadAndRest?.();
                     },
                }}
                onRow={(record)=>{
                 return {
                   onClick:()=>{
                   const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedRecords([record]);
                     setSelectedLineKeys([k]);
                     table_ref2.current?.reloadAndRest?.();
                   },
                }
               }}
                request={async (params)=>{
                    //const id=selectedRowKeys.length==0?0:selectedRowKeys[0];
                    const x=await s_getPostWareInfo({source:'v_ware',x_id:1,id:0})
                    return{
                        data:x.data,
                        success:true,
                    }
                }}
                scroll={{
                    y:'50vh',
                }}
                options={false}
                />
              </ProCard>
          </Col>
          <Col span={16}>
          <ProCard title='库位明细'  style={{height:'75vh'}}
           extra={<Space>
            <Button onClick={()=>add()}>新 增</Button>
            <Button onClick={()=>edit()}>编 辑</Button>
            <Button onClick={()=>operate(2)}>关闭</Button>
            <Button onClick={()=>operate(3)}>删 除</Button>
            <Button onClick={()=>operate(1)}>恢 复</Button>
            <ImportData  x_id={1} source='importdata' tdata={{data:'base_warehouse_pos'}}
                operater_id={initialState?.currentUser?.userid}  />
           </Space>}
          >
          <ProTable<DataType2>
            rowKey='id'
             search={false}
             actionRef={table_ref2}
             columns={columns2}
             rowSelection={{
                 type:'radio',
                 selectedRowKeys:selectedLineKeys2,
                 onChange:(selectedRowKeys,selectedRows)=>{
                         setSelectedRecords2(selectedRows);
                         setSelectedLineKeys2(selectedRowKeys);
                 },
             }}
              onRow={(record)=>{
              return {
              onClick:()=>{
                const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedLineKeys2([k]);
                     setSelectedRecords2([record]);
              },
            }
           }}
             request={async (params)=>{
                 //const id=selectedRowKeys.length==0?0:selectedRowKeys[0];
                 const x=await s_getTableInfo({source:'v_warehouse_pos',x_id:1,id:
                          selectedRecords.length>0?selectedRecords[0].id:0})
                 return{
                     data:x.data,
                     success:true,
                 }
             }}
             scroll={{
                y:500,
            }}
            options={false}
           />
           </ProCard>
          </Col>

        </Row>
       
        {/* 库位编辑表单 */}
        <Modal open={open} title={etype==0?'编辑库位档案':'新增库位档案'} closable 
            destroyOnClose onCancel={()=>setOpen(false)}  
            onOk={()=>form_ref.current?.submit()} width={660}>
           <ProForm 
                   style={{marginLeft:100}}
                   formRef={form_ref} 
                   submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                   onFinish={()=>save()}
                   initialValues={etype==0&&selectedRecords2.length>0?{
                   ...selectedRecords2[0]
                   }:{
                    operate_time:moment().format('YYYY-MM-DD'),operater_id:initialState?.currentUser?.userid,type:1,status:1,
                  }}
           >
                  <ProFormText name='warehouse_id' hidden={true}/>
                  <ProFormText name='id' hidden={true} />
                  <ProFormText name='code' label='库位编码' width={200} rules={[{required:true,message:'必输项'}]}/>
                  <ProFormText name='name' label='库位名称' width={200}  rules={[{required:true,message:'必输项'}]}/>
                  <ProFormRadio.Group name='type' label='类型' width={200}
                       options={[{value:1,label:'存储'},{value:2,label:'暂存'},
                                {value:3,label:'周转'},{value:4,label:'其他'}]} />
                  <ProFormRadio.Group name='status' label='状态' width={200}
                       options={[{value:1,label:'正常'},{value:2,label:'关闭'},{value:3,label:'删除'}]} />
                  <ProFormDatePicker name='operate_time' width={200}  label='操作时间'/>
                  <ProFormSelect name='operater_id' width={200}  label='操作人'
                        showSearch
                        request={async ()=>{
                             const x=await s_getSelectData({x_id:1,source:'base_person'});
                             return x.data;
                         }}
                  />
                
               </ProForm>
        </Modal>
         
        </>
    );
}

export default App;